/**
 * Created by xiaoz on 16/8/13.
 */
define(["utils","base"],function(utils,baseClass){

  var MenuItem = function(config){
      var _this = this;
      this.datasource = config.datasource;
      var menuConfig = config.menu.config;
      this.pageview = config.menu.pageview;
      this.config = config;
      this.menu = config.menu;
      this.hrefMarkArr = [];
      config.menu.items.push(this);
      if(this.datasource&&this.datasource.href){
        var href_arr = this.datasource.href.split("/");
        var Re = [];
        for(var i=0,j=href_arr.length;i<j;i++){
          var h = href_arr[i];
          if(h!=="/"){
            this.hrefMarkArr.push(h);
          }
        }
      }

      var isGroupHeaderItem = config.isGroupHeaderItem;

      this.selectedItemClassName = menuConfig.selectedItemClassName || "yy-item-selected";

      var itemHoverClassName = menuConfig.itemHoverClassName || "";
      var className = config.noHover===true?"yy-menuitem ":"yy-menuitem "+itemHoverClassName;
      this.$el = $("<div class='"+className+"'></div>");
      this.parent = config.parent;
      var iconWrapper = $("<div class='yy-menu-icon-wrap'></div>");

      if(this.datasource.icon){
        var font_arr = this.datasource.icon.split("_");
        var font_family,font_code;
        if(font_arr.length==2){
            font_family = font_arr[0];
            font_code = font_arr[1];
            this.iconDom = $('<i  class="yy-menu-icon" data-code="'+font_code+'" data-icon="&#x'+font_code+';"></i>');
            menuConfig.iconStyle = menuConfig.iconStyle||{};
            menuConfig.iconStyle.fontFamily = font_family;
            utils.css(this.iconDom,menuConfig.iconStyle);
            iconWrapper.append(this.iconDom);
        }else if(this.datasource.icon){
            this.iconDom = $('<i  class="yy-menu-icon"></i>');
            this.iconDom.addClass(this.datasource.icon);
            menuConfig.iconStyle = menuConfig.iconStyle||{};
            utils.css(this.iconDom,menuConfig.iconStyle);
            iconWrapper.append(this.iconDom);
        }
      }
      this.$el.append(iconWrapper);

      if(this.datasource.text){
        var textWrapper = $("<div class='yy-menu-text-wrap'></div>");
        this.textDom = $("<span class='yy-menu-text'>"+this.datasource.text+"</span>");
        textWrapper.append(this.textDom);
        this.$el.append(textWrapper);
      }
      if(isGroupHeaderItem){
        var iconClass = this.config.datasource.rightIcon || "yy-fontawesome";
        var toggleIconWrapper = $("<div class='yy-menu-toggle-icon-wrap'><span class='"+iconClass+"'></span></div>");
        this.$el.append(toggleIconWrapper);
      }
      var group = config.group;
      this.$el.bind("click",function(){
        if(config.noHover===true){
          if(group){
            group.toggle();
          }
        }else{
          var urlParams = _this.menu.config.urlParamKeys;
          var params = {};
          if(urlParams&& (urlParams instanceof Array)){
            for(var i=0,j=urlParams.length;i<j;i++){
              var pKey = urlParams[i];
              params[pKey] = _this.datasource[pKey];
            }
          }
          _this.pageview.go(_this.datasource.href,params);
        }
      });
  }

  MenuItem.prototype ={
      setText:function(text){
          this.textDom.html(text);
      },
    selected:function(){
      this.$el.addClass(this.selectedItemClassName);
    },
    unSelected:function(){
      this.$el.removeClass(this.selectedItemClassName);
    }
  } ;



  var MenuGroup = function(config){
      var _this = this;

      this.config = config;
      this.pageview = config.menu.pageview;
      this.$el = $("<div class='yy-menugroup'></div>");
      this.datasource = config.datasource;
      this.parent = config.parent;
      this.isOpen = true;

      this.menuItem = new MenuItem({
        type:"menuitem",
        parent:this,
        datasource:this.datasource,
        menu:config.menu,
        group:this,
        isGroupHeaderItem:true,
        noHover:true
      });
      this.groupWrapper = $("<div class='yy-menugroup-wrapper'></div>");
      this.bindData(this.datasource.children);
      this.$el.append(this.menuItem.$el).append(this.groupWrapper);
  }

  MenuGroup.prototype.toggle = function(){
    if(this.isOpen){
      this.isOpen = false;
      this.menuItem.$el.addClass("yy-menu-headeritem-close");
      this.groupWrapper.css({height:0});
    }else{
      this.isOpen = true;
      this.groupWrapper.css({height:"auto"});
      this.menuItem.$el.removeClass("yy-menu-headeritem-close");
    }
  };

  MenuGroup.prototype.bindData = function(data){
    if(!(data instanceof Array)){
      console.error("menu 的数据必须为数组");
    }
    for(var i=0,j=data.length;i<j;i++){
      var itemData = data[i];
      var item;
      var children = itemData.children||[];
      if(!(children instanceof Array)){
        console.error("menu 中每项数据的children字段必须为数字");
      }
      if(children.length>0){
        item = new MenuGroup({
          type:"menugroup",
          parent:this,
          menu:this.config.menu,
          datasource:itemData
        });
      }else{
        item = new MenuItem({
          type:"menuitem",
          parent:this,
          menu:this.config.menu,
          datasource:itemData
        });
        if(itemData.key){
            this.parent.itemDict[itemData.key] = item;
        }
      }
      this.groupWrapper.append(item.$el);
    }
  }

    var Component = function(config){
        var _this = this;
        Component.baseConstructor.call(this,config);
        this.$el.addClass("yy-menu");
        this.items=[];
        this.itemDict = {};

        this.bindData(this.config.items);

        this.$el.attr('unselectable','on').bind('selectstart', function(){ return false; });

        var pluginName = this.config.comKey + "_change";
        if (this.pageview.plugin[pluginName]) {
            this.changeMethod = this.pageview.plugin[pluginName];
        }

        this.registerHashChange();


    }

    utils.extendClass(Component,baseClass);

    Component.prototype.registerHashChange = function(){
      var key  = this.pageview.config.pageKey+"_"+this.config.comKey;
      this.pageview.registerHashChangeComponent[key] = this;
      this.hashChange();
    };
    Component.prototype.hashChange = function(){
      if(this.selectedItem){
        this.selectedItem.unSelected();
      }
      //todo 直接取pageview的pagecontainer的this.router
      var curHrefMarkArr = this.pageview.pageManager.getPageNameArrFromUrl();

      for(var i=0,j=this.items.length;i<j;i++){
        var item = this.items[i];
        var len = item.hrefMarkArr.length;
        if(curHrefMarkArr.length<len||len==0){
          continue;
        }
        var temArr = [];
        for(var n=0;n<len;n++){
          temArr.push(curHrefMarkArr[n]);
        }

        if(item.hrefMarkArr.join("_") === temArr.join("_")){
          this.selectedItem = item;
          item.selected();
          break;
        }
      }

      if(this.changeMethod){
          this.changeMethod.call(this.pageview.plugin, this,{selectedItem:this.selectedItem});
      }
    };
    Component.prototype.cancelHashChange = function(){
      var key  = this.pageview.config.pageKey+"_"+this.config.comKey;
      delete this.pageview.registerHashChangeComponent[key];
    };

    Component.prototype.addMenu = function(data,needChange){

      if(!(data instanceof Array)){
        console.error("menu 的数据必须为数组");
      }
      for(var i=0,j=data.length;i<j;i++){
        var itemData = data[i];
        var item;
        var children = itemData.children||[];
        if(!(children instanceof Array)){
          console.error("menu 中每项数据的children字段必须为数字");
        }
        if(children.length>0){
          item = new MenuGroup({
            type:"menugroup",
            parent:this,
            menu:this,
            datasource:itemData
          });
        }else{
          item = new MenuItem({
            type:"menuitem",
            parent:this,
            menu:this,
            datasource:itemData
          });
          if(itemData.key){
              this.itemDict[itemData.key] = item;
          }
        }
        this.$el.append(item.$el);

      }
      if(needChange!==false){
        this.hashChange();
      }
    };

    Component.prototype.bindData = function(data){
      this.addMenu(data,false);
    }

    return Component;
});
